package com.py.framework.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.py.framework.common.Constants;
import com.py.framework.core.utils.DateUtils;
import com.py.framework.dao.SysMsgDao;
import com.py.framework.entity.AreaEntity;
import com.py.framework.entity.MsgDetailEntity;
import com.py.framework.entity.MsgRecordEntity;
import com.py.framework.entity.OfficeEntity;
import com.py.framework.entity.SysMsgEntity;
import com.py.framework.entity.UserEntity;
import com.py.framework.enums.RevieveType;
import com.py.framework.schedule.MsgRecordScheduler;
import com.py.framework.service.AreaService;
import com.py.framework.service.OfficeService;
import com.py.framework.service.SysMsgService;
import com.py.framework.service.UserService;

/**
 * 系统消息Service实现
 * 
 * @author Leegern
 * @date 2018年4月24日
 */
@Service
public class SysMsgServiceImpl implements SysMsgService {

	@Autowired
	private SysMsgDao sysMsgDao;
	@Autowired
	private MsgRecordScheduler msgRecordScheduler;
	@Autowired
	private AreaService areaService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private UserService userService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.SysMsgService#queryMsgForPage(java.util.Map)
	 */
	@Override
	public List<SysMsgEntity> queryMsgForPage(Map<String, Object> params) {
		return sysMsgDao.querySysMsgForPage(params);
	}
	public List<SysMsgEntity> queryBMMsgForPage(Map<String, Object> params) {
		return sysMsgDao.queryBMMsgForPage(params);
	}
	public List<SysMsgEntity> queryQYMsgForPage(Map<String, Object> params) {
		return sysMsgDao.queryQYMsgForPage(params);
	}
	
	

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.SysMsgService#queryNoticeMsgForPage(java.util.
	 * Map)
	 */
	@Override
	public List<SysMsgEntity> queryNoticeMsgForPage(Map<String, Object> params) {
		return sysMsgDao.queryNoticeMsgForPage(params);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.SysMsgService#findOneMsg(long)
	 */
	@Override
	public SysMsgEntity findOneMsg(long id) {
		SysMsgEntity entity = null;
		List<MsgDetailEntity> details = null;
		UserEntity user = null;
		AreaEntity area = null;
		OfficeEntity office = null;
		if (id > Constants.NUMBER_ZERO) {
			entity = sysMsgDao.findOneMsg(id);
			if (null != entity && !CollectionUtils.isEmpty((details = entity.getDetails()))) {
				for (MsgDetailEntity detail : details) {
					// 用户
					if (detail.getRevieveType() == RevieveType.TYPE_1.getValue()) {
						user = userService.findOneUser(detail.getReviever());
						if (null != user) {
							detail.setRevieverName(user.getRealName());
						}
					}
					// 区域
					else if (detail.getRevieveType() == RevieveType.TYPE_2.getValue()) {
						area = areaService.findOneArea(detail.getReviever());
						if (null != area) {
							detail.setRevieverName(area.getAreaName());
						}
					}
					// 部门
					else if (detail.getRevieveType() == RevieveType.TYPE_3.getValue()) {
						office = officeService.findOneOffice(detail.getReviever());
						if (null != office) {
							detail.setRevieverName(office.getOfficeName());
						}
					}
					// 全部
					else if (detail.getRevieveType() == RevieveType.TYPE_4.getValue()) {
						detail.setRevieverName("全部");
					}
				}
			}
		}
		return entity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.SysMsgService#findOneNoticeMsg(long)
	 */
	@Override
	public SysMsgEntity findOneNoticeMsg(long id) {
		SysMsgEntity entity = null;
		if (id > Constants.NUMBER_ZERO) {
			entity = sysMsgDao.findOneMsg(id);
		}
		return entity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.SysMsgService#queryMsgDetail(long)
	 */
	@Override
	public List<MsgDetailEntity> queryMsgDetail(long msgId) {
		if (msgId > Constants.NUMBER_ZERO) {
			return sysMsgDao.queryMsgDetail(msgId);
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.SysMsgService#queryMsgRecord(long, long,
	 * int)
	 */
	@Override
	public List<MsgRecordEntity> queryMsgRecord(long msgId, long userId, int msgStatus) {
		if (msgId > Constants.NUMBER_ZERO) {
			return sysMsgDao.queryMsgRecord(msgId, userId, msgStatus);
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.SysMsgService#addMsgInfo(com.py.framework.entity
	 * .SysMsgEntity)
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int addMsgInfo(SysMsgEntity entity) {
		if (null == entity || CollectionUtils.isEmpty(entity.getDetails())) {
			return 0;
		}
		return this.saveMsg(entity, Constants.NUMBER_ONE);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.SysMsgService#updateMsgInfo(com.py.framework.
	 * entity.SysMsgEntity)
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int updateMsgInfo(SysMsgEntity entity) {
		if (null == entity || CollectionUtils.isEmpty(entity.getDetails())) {
			return 0;
		}
		return this.saveMsg(entity, Constants.NUMBER_ZERO);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.SysMsgService#updateMsgRecordStatus(long,
	 * int)
	 */
	@Override
	public int updateMsgRecordStatus(long recordId, int msgStatus) {
		if (recordId > Constants.NUMBER_ZERO && msgStatus > Constants.NUMBER_ZERO) {
			Map<String, Object> params = new HashMap<>();
			params.put("recordId", recordId);
			params.put("msgStatus", msgStatus);
			params.put("updateTime", new Timestamp(System.currentTimeMillis()));
			return sysMsgDao.updateMsgRecordStatus(params);
		}
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.SysMsgService#batchDelMsg(java.util.List)
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int batchDelMsg(List<Long> ids) {
		int flag = 0;
		if (!CollectionUtils.isEmpty(ids)) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("ids", ids);
			params.put("updateTime", new Timestamp(DateUtils.getCurrentDateTime().getTime()));
			// 批量删除消息
			flag = sysMsgDao.batchDelMsg(params);
			// 批量删除消息详情
			sysMsgDao.batchDelMsgDetail(params);
			// 批量删除消息记录
			sysMsgDao.batchDelMsgRecord(params);
		}
		return flag;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.SysMsgService#batchAddMsgDetailInfo(java.util.
	 * List)
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int batchAddMsgDetailInfo(List<MsgDetailEntity> datas) {
		if (!CollectionUtils.isEmpty(datas)) {
			for (MsgDetailEntity entity : datas) {
				sysMsgDao.addMsgDetailInfo(entity);
			}
			return datas.size();
		}
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.SysMsgService#batchAddMsgRecordInfo(java.util.
	 * List)
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int batchAddMsgRecordInfo(List<MsgRecordEntity> datas) {
		if (!CollectionUtils.isEmpty(datas)) {
			return sysMsgDao.batchAddMsgRecordInfo(datas);
		}
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.SysMsgService#batchDelMsgDetail(java.util.List)
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int batchDelMsgDetail(List<Long> ids) {
		if (!CollectionUtils.isEmpty(ids)) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("ids", ids);
			params.put("updateTime", new Timestamp(DateUtils.getCurrentDateTime().getTime()));
			return sysMsgDao.batchDelMsgDetail(params);
		}
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.SysMsgService#batchDelMsgRecord(java.util.List)
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int batchDelMsgRecord(List<Long> ids) {
		if (!CollectionUtils.isEmpty(ids)) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("recordIds", ids);
			params.put("updateTime", new Timestamp(System.currentTimeMillis()));
			return sysMsgDao.batchDelMsgRecord(params);
		}
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.SysMsgService#getAreasByPid(long)
	 */
	@Override
	public List<Map<String, Object>> getAreasByPid(long parentId) {
		List<Map<String, Object>> result = new ArrayList<>();
		Map<String, Object> item = null;
		List<UserEntity> users = null;
		int count = 0;
		List<UserEntity> parentDeptUsers = null;
		List<AreaEntity> datas = null;
		if (parentId > Constants.NUMBER_ZERO) {
			datas = areaService.getAreasByPid(parentId);
			parentDeptUsers = userService.getUsersByAreaId(String.valueOf(parentId));

		} else {
			datas = areaService.getRootArea();
		}
		if (null != datas) {
			for (AreaEntity areaEntity : datas) {
				item = new HashMap<>();
				item.put("areaId", areaEntity.getId());
				item.put("areaName", areaEntity.getAreaName());
				item.put("parentAreaId", areaEntity.getParentId());
				item.put("type", "2");
				users = userService.getUsersByAreaId(String.valueOf(areaEntity.getId()));
				if (!CollectionUtils.isEmpty(users)) {
					count = users.size();
				}
				item.put("count", count);
				result.add(item);
			}
		}
		if (parentDeptUsers != null) {

			for (UserEntity user : parentDeptUsers) {
				item = new HashMap<>();
				item.put("type", "1");
				item.put("userId", user.getId());
				item.put("userName", user.getRealName());

				result.add(item);
				// 加进展示列表

			}

		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.SysMsgService#getOfficesByPid(long)
	 */
	@Override
	public List<Map<String, Object>> getOfficesByPid(long parentId) {
		List<Map<String, Object>> result = new ArrayList<>();
		Map<String, Object> item = null;
		List<UserEntity> users = null;

		List<OfficeEntity> datas = null;
		List<UserEntity> parentDeptUsers = null;
		if (parentId > Constants.NUMBER_ZERO) {
			datas = officeService.getOfficesByPid(parentId);
			parentDeptUsers = userService.getDirectUsersByOfficeIds(String.valueOf(parentId));

		} else {
			datas = officeService.getRootOffices();
		}
		if (null != datas) {
			for (OfficeEntity entity : datas) {
				int count = 0;
				item = new HashMap<>();
				item.put("officeId", entity.getId());
				item.put("officeName", entity.getOfficeName());
				item.put("parentOfficeId", entity.getParentId());
				item.put("type", "3");

				users = userService.getUsersByOfficeId(String.valueOf(entity.getId()));
				if (!CollectionUtils.isEmpty(users)) {
					count = users.size();
				}
				item.put("count", count);
				result.add(item);
			}
		}

		if (parentDeptUsers != null) {

			for (UserEntity user : parentDeptUsers) {
				item = new HashMap<>();
				item.put("type", "1");
				item.put("userId", user.getId());
				item.put("userName", user.getRealName());

				result.add(item);
				// 加进展示列表

			}

		}
		return result;
	}

	/**
	 * 保存消息实体
	 * 
	 * @param entity
	 *            消息实体
	 * @param type
	 *            操作类型，1：添加
	 * @return
	 */
	private int saveMsg(SysMsgEntity entity, int type) {
		int flag = 0;

		entity.setUpdateTime(new Timestamp(System.currentTimeMillis()));

		// 添加
		if (type == Constants.NUMBER_ONE) {
			entity.setCreateTime(new Timestamp(System.currentTimeMillis()));
			entity.setDelFlag(Constants.NUMBER_ONE);
			if (entity.getMsgType() == Constants.NUMBER_ZERO) {
				entity.setMsgType(Constants.NUMBER_ONE);
			}
			flag = sysMsgDao.addMsgInfo(entity);
		}
		// 修改
		else {
			flag = sysMsgDao.updateMsgInfo(entity);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("ids", Arrays.asList(new Long[] { entity.getId() }));
			params.put("updateTime", new Timestamp(DateUtils.getCurrentDateTime().getTime()));
			// 批量删除消息详情
			sysMsgDao.batchDelMsgDetail(params);
			// 批量删除消息记录
			sysMsgDao.batchDelMsgRecord(params);
		}
		List<MsgDetailEntity> details = entity.getDetails();
		if (!CollectionUtils.isEmpty(details)) {
			for (MsgDetailEntity detail : details) {
				detail.setCreateTime(new Timestamp(System.currentTimeMillis()));
				detail.setUpdateTime(new Timestamp(System.currentTimeMillis()));
				detail.setDelFlag(Constants.NUMBER_ONE);
				detail.setMsgId(entity.getId());
				// 添加详情信息
				sysMsgDao.addMsgDetailInfo(detail);
			}

			// 批量添加记录信息
			this.msgRecordScheduler.doSubmit(details, entity.getId());
		}
		//sysMsgDao.deleMsgDetailInfoRep(entity.getId());
		return flag;
	}

	/**
	 *
	 * @Function 获取未读消息数量
	 * @FileName SysMsgServiceImpl.java
	 * @MethodName getUnreadNum
	 * @param userId
	 *            用户ID
	 * @return
	 * @Date 2018年7月30日 下午3:55:32
	 * @Author Min DongXv
	 *
	 */
	@Override
	public int getUnreadNum(long userId) {
		return sysMsgDao.getUnreadNum(userId);
	}

	@Override
	public int getDataCollectionMessageNum() {

		return sysMsgDao.selectDataCollectionMessageNum();
	}

	@Override
	public List<MsgRecordEntity> queryReadOrNot(long msgId, long userId, int msgStatus) {
		// TODO Auto-generated method stub
		return sysMsgDao.queryReadOrNot(msgId, userId, msgStatus);
	}

	@Override
	public int deleMsgRecordInfo(long msgId) {
		// TODO Auto-generated method stub
		return sysMsgDao.deleMsgRecordInfo(msgId);
	}
}